﻿using Microsoft.Win32;
using SHKF.B2C.Mannage.AdminUI.Model;
using SHKF.B2C.Mannage.AdminUI.Network;
using SHKF.B2C.Model;
using SHKF.B2C.Model.Dto;
using SHKF.B2C.Model.Dto.Center;
using SHKF.B2C.Model.Entity.Center;
using SHKF.B2C.Model.Req;
using SHKF.B2C.YouZanYun.Model.Inter.Category;
using SHKF.B2C.YouZanYun.Model.Inter.CategoryPropertys;
using SHKF.B2C.YouZanYun.Model.Inter.Center;
using SHKF.B2C.YouZanYun.Model.Inter.Image;
using SHKF.B2C.YouZanYun.Model.Inter.ImgUpload;
using SHKF.B2C.YouZanYun.Model.Inter.Item;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WQDSkin.Forms.Component;

namespace SHKF.B2C.Mannage.AdminUI.View.Yzy.Import
{
    /// <summary>
    /// frmImport.xaml 的交互逻辑
    /// </summary>
    public partial class frmImport : BasePage
    {
        private ImportViewModel data;
        private string authority_id = ""; //第三方门店ID
        private List<ProductInfo> dataList; //已经存在数据
        private SolidColorBrush errorBackground = new SolidColorBrush(Colors.Red);
        private SolidColorBrush errorForeground = new SolidColorBrush(Colors.White);
        private List<string> errorProductList = new List<string>(); //存储没有图片的产品名
        private long _leaf_category_id = 0;

        private HttpClientYouZanYun httpYzy;

        public List<ImageItem> tempImageList = new List<ImageItem>(); //选择的图片
        public frmImport()
        {
            InitializeComponent();
        }

        private void BasePage_Loaded(object sender, RoutedEventArgs e)
        {
            this.data = (ImportViewModel)this.DataContext;

            LoadAuthority(); 
        }

        #region 1.加载图片

        //1.加载图片
        private void btnLoadImage_Click(object sender, RoutedEventArgs e)
        {
            frmSearchImage frm = new frmSearchImage();
            frm.authority_id = authority_id;
            if (frm.ShowDialog() == true)
            {
                //在导入的时候重新获取
                //tempImageList.Clear();
                //foreach (ImageItem image in frm.SelectedImages)
                //{
                //    tempImageList.Add(image);
                //}.

                 
                ImageItem data1 = frm.SelectedImages[0];
                string url1 = data1.url;
                BitmapImage bmp1 = new BitmapImage(new Uri(url1));
                this.txtID1.Text = data1.media_id.ToString();
                this.img1.DataContext = data1;
                this.img1.Source = bmp1;


                ImageItem data2 = frm.SelectedImages[1];
                string url2 = data2.url;
                BitmapImage bmp2 = new BitmapImage(new Uri(url2));
                this.img2.DataContext = data2;
                this.img2.Source = bmp2;
                this.txtID2.Text = data2.media_id.ToString();

                ImageItem data3 = frm.SelectedImages[2];
                string url3 = data3.url;
                BitmapImage bmp3 = new BitmapImage(new Uri(url3));
                this.img3.DataContext = data3;
                this.img3.Source = bmp3;
                this.txtID3.Text = data3.media_id.ToString();

                //    //处理图片
                //    this.errorProductList = new List<string>();

                //SolidColorBrush bg = new SolidColorBrush(Colors.Red);
                //SolidColorBrush Foreground = new SolidColorBrush(Colors.White);

                ////产品
                //for (int i = 0; i < this.data.Products.Count; i++)
                //{ 
                //    ProductInfoViewModel product = this.data.Products[i];
                //    product.media_id.Clear();

                //    if (string.IsNullOrEmpty(product.ImageList))
                //    {
                //        if (!errorProductList.Contains(product.ProductName))
                //        { 
                //            errorProductList.Add(product.ProductName);
                //        }

                //        SetErrorCell(i); 
                //        product.Msg = "图片信息不存在";
                //    }
                //    else
                //    {
                //        string[] imgList = product.ImageList.Split(",");
                //        foreach (KeyValuePair<long, List<ImageItem>> image in frm.tempImageList)
                //        {
                //            foreach (string imageName in imgList)
                //            {
                //                List<ImageItem> items = image.Value.FindAll(oo => oo.title.Contains(imageName));
                //                if (items.Count > 0)
                //                {
                //                    long media_id = items[0].media_id;
                //                    product.media_id.Add(media_id);
                //                }
                //            }

                //            //如果图片少地3个，无法保存
                //            if (product.media_id.Count < 3)
                //            {
                //                if (!errorProductList.Contains(product.ProductName))
                //                {
                //                    errorProductList.Add(product.ProductName);
                //                }

                //                SetErrorCell(i);
                //                product.Msg = "图片少于3张";
                //            }
                //        }
                //    }
                //}

                //标识是否有错
                this.btnImport.IsEnabled = this.tempImageList.Count >= 3;
            }
        }
         
        private void btnAddImage1_Click(object sender, RoutedEventArgs e)
        {
            AddImage("1");
        }

        private void btnAddImage2_Click(object sender, RoutedEventArgs e)
        {
            AddImage("2");
        }

        private void btnAddImage3_Click(object sender, RoutedEventArgs e)
        {
            AddImage("3");
        }

        private void AddImage(string index)
        {
            frmSearchImage frm = new frmSearchImage();
            frm.SelectCount = 1;
            frm.authority_id = authority_id;
            if (frm.ShowDialog() == true)
            {
                ImageItem itemSelected = frm.SelectedImages[0];  
                Image img = (Image)this.FindName($"img{index}");
                img.DataContext = itemSelected;
                BitmapImage bmp1 = new BitmapImage(new Uri(itemSelected.url));
                img.Source = bmp1;

                TextBox txt = (TextBox)this.FindName($"txtID{index}");
                txt.Text = itemSelected.media_id.ToString();
            }
        }
         
        #endregion

        #region 2.选择产品分类
         
        //private void btnSelectedCategory_Click(object sender, RoutedEventArgs e)
        //{
        //    frmSearchProductCategory frm = new frmSearchProductCategory();
        //    frm.authority_id = authority_id;
        //    if (frm.ShowDialog() == true)
        //    {
        //        long leaf_category_id = frm.leaf_category_id;
        //    }
        //}
         
        private async void LoadItemCategory1()
        {
            CategoryRequest category1 = await this.httpYzy.GetCategoryChildren(0);
            if (category1.data != null)
            {
                foreach (CategoryData item in category1.data)
                {
                    CategoryRequest category2 = await this.httpYzy.GetCategoryChildren(item.id);
                    item.data = category2.data;
                }

                this.tvLevel1.ItemsSource = category1.data;
            }
            else
            {
                MessageBox.Show(category1.message);
            }
        }

        private void tvLevel1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            TreeView tv = (TreeView)sender;
            CategoryData data = (CategoryData)tv.SelectedValue;
            LoadItemCategory(this.tvLevel2, data.id);
        }

        private void tvLevel2_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            TreeView tv = (TreeView)sender;
            if (tv.SelectedValue != null)
            {
                CategoryData data = (CategoryData)tv.SelectedValue;
                LoadItemCategory(this.tvLevel3, data.id);
            }
        }

        private void tvLevel3_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            TreeView tv = (TreeView)sender;
            if (tv.SelectedValue != null)
            {
                CategoryData data = (CategoryData)tv.SelectedValue;
                LoadItemCategory(this.tvLevel4, data.id);
            }
        }

        private async void LoadItemCategory(TreeView tv, long id)
        {
            Setleaf_category_id();
            CategoryRequest category = await this.httpYzy.GetCategoryChildren(id);
            if (category.data != null)
            {
                tv.ItemsSource = category.data;
            }
            else
            {
                MessageBox.Show(category.message);
            }
        }

        public void Setleaf_category_id()
        { 
            if (this.tvLevel1.SelectedValue != null)
            {
                CategoryData data = (CategoryData)tvLevel1.SelectedValue;
                if (!data.has_children)
                {
                    _leaf_category_id = data.id;
                }
            }

            if (this.tvLevel2.SelectedValue != null)
            {
                CategoryData data = (CategoryData)tvLevel2.SelectedValue;
                if (!data.has_children)
                {
                    _leaf_category_id = data.id;
                }
            }
            if (this.tvLevel3.SelectedValue != null)
            {
                CategoryData data = (CategoryData)tvLevel3.SelectedValue;
                if (!data.has_children)
                {
                    _leaf_category_id = data.id;
                }
            }

            if (this.tvLevel4.SelectedValue != null)
            {
                CategoryData data = (CategoryData)tvLevel4.SelectedValue;
                if (!data.has_children)
                {
                    _leaf_category_id = data.id;
                }
            }

        }

        #endregion

        #region 3.选择Excel 

        private void btnImportExcel_Click(object sender, RoutedEventArgs e)
        {
            this.InitImageList();
            if (this.tempImageList.Count < 3)
            {
                MessageBox.Show("最少选择3张默认图片");
                return;
            }

            LoadProduct();
            this.errorProductList.Clear();

            if (this.dgv.ItemsSource == null)
                this.dgv.ItemsSource = this.data.Products;

            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.DefaultExt = ".xlsx";
            openFileDialog.Filter = "Excel文件 (.xlsx)|*.xlsx";

            if (openFileDialog.ShowDialog() == true)
            {
                this.data.Products.Clear();
                this.data.CurrentValue = 0;

                string fileName = openFileDialog.FileName;
                ExcelHelper excelHelper = new ExcelHelper(fileName);

                //初始化列
                foreach (DataGridColumn dataGridColumn in this.dgv.Columns)
                {
                    string dataColumnName = "";
                    if (dataGridColumn is DataGridTextColumn)
                    {
                        dataColumnName = ((Binding)((DataGridTextColumn)dataGridColumn).Binding).Path.Path;
                    }
                    excelHelper.Columns.Add(dataGridColumn.Header.ToString(), dataColumnName);
                }

                ObservableCollection<ProductInfoViewModel> data = excelHelper.ExcelToList<ProductInfoViewModel>("Sheet1", true);
                bool b1 = false;

                if (this.dataList != null)
                {
                    b1 = data.Count > 0;

                    for (int i = data.Count - 1; i >= 0; i--)
                    {
                        ProductInfoViewModel product = data[i];
                        product.CompanySN = (int)this.data.Company.SN;

                        //如果B2C数据库已经存在了，则删除导入的数据
                        ProductInfo old = this.dataList.Find(oo => oo.Upc == product.Upc);
                        if (old != null)
                        {
                            data.RemoveAt(i);
                        }
                        else
                        {
                            ////验证图片信息
                            //if (string.IsNullOrEmpty(product.ImageList))
                            //{
                            //    product.Msg = "图片不存在";
                            //}
                            //else
                            //{
                            //    if (product.ImageList.Split(",").Length < 3)
                            //    {
                            //        product.Msg = "图片少于3张";
                            //    }　
                            //}

                            //if (!string.IsNullOrEmpty( product.Msg ))
                            //{ 
                            //    this.errorProductList.Add(product.ProductName);
                            //}

                            foreach (ImageItem imageItem in this.tempImageList)
                            {
                                product.media_id.Add(imageItem.media_id);
                            }

                            this.data.Products.Add(product);
                        }
                    }
                }

                if (b1 && data.Count <= 0)
                {
                    MessageBox.Show("产品在B2C数据库中已经存在");
                }

                this.btnImport.IsEnabled = this.data.Products.Count > 0;
                this.data.CurrentValue = 0;

                this.data.Total = data.Count;

                //this.btnLoadImage.IsEnabled = this.errorProductList.Count == 0 && this.data.Total > 0;
            }
        }

        #endregion

        //4.开始导入
        private void InitImageList()
        {
            this.tempImageList.Clear();
            if(this.img1.DataContext != null)
            {
                ImageItem item1 = this.img1.DataContext as ImageItem;
                if(item1 != null)
                {
                    this.tempImageList.Add(item1);
                } 
            }

            if (this.img2.DataContext != null)
            {
                ImageItem item2 = this.img2.DataContext as ImageItem;

                if (item2 != null)
                {
                    this.tempImageList.Add(item2);
                }
            }

            if (this.img3.DataContext != null)
            {
                ImageItem item3 = this.img3.DataContext as ImageItem; 
                if (item3 != null)
                {
                    this.tempImageList.Add(item3);

                }
            } 
        }

        private async void btnImport_Click(object sender, RoutedEventArgs e)
        {
            if (this._leaf_category_id == 0)
            { 
                MessageBox.Show("请选择产品类目");
                return;
            } 

            if (this.dgv.ItemsSource == null)
            {
                MessageBox.Show("请导入Excel");
                return;
            }

            InitImageList();

            if (this.tempImageList.Count < 3)
            {
                MessageBox.Show("最少选择三张图片");
                return;
            }

          
            this.data.CurrentValue = 0;

            ObservableCollection<ProductInfoViewModel> products = this.data.Products;
            if (products != null && products.Count > 0)
            { 
                try
                {
                    this.btnImport.IsEnabled = false;
 
                    //公共参数 
                    CategoryPropertysResult result = await this.httpYzy.GetCategoryById(authority_id, this._leaf_category_id);

                    if (result.success && result.data != null
                        && result.data.public_propertys != null
                        && result.data.public_propertys.Count > 0)
                    {
                        await Task.Factory.StartNew(() =>
                        {
                            for (int i = 0; i < this.data.Products.Count; i++)
                            {
                                ProductInfoViewModel product = this.data.Products[i];
                                List<long> media_id = product.media_id;
                                SaveData(i, product, result.data.public_propertys, this._leaf_category_id);
                                Thread.Sleep(200);
                            }
                        });
                    }
                    else
                    {
                        MessageBox.Show("所选类目没有公共参数");
                        return;
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
            else
            {
                MessageBox.Show("请选择数据源");
            }
        }
     
        private void dgv_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }
         
        //用于过滤产品
        private async void LoadProduct()
        {
            long CompnaySN = this.data.Company.SN;
            ProductListDto dto = await GL.HttpClientManage.QueryProduct(CompnaySN, 0, "");
            if (dto.error == null)
            {
                dataList = dto.data;
            }
            else
            {
                MessageBox.Show(dto.error.msg);
            }
        }

        //用于获取token
        private async void LoadAuthority()
        {
            DataDto dto = await GL.HttpClientManage.ShopGetKdtId(data.Company.SN);
            if (dto.error == null)
            {
                if (dto.data == "0")
                {
                    MessageBox.Show(data.Company.CompanyName + "没有配置有赞云总部ID");
                    this.btnLoadImage.IsEnabled = false;
                }
                else
                {
                    this.btnLoadImage.IsEnabled = true;
                    authority_id = dto.data;

                    this.httpYzy = GL.CreateYouZanYun();
                    this.httpYzy.authority_id = authority_id;

                    LoadItemCategory1();
                }
            }
        }

        private async void SaveData(int rowIndex, ProductInfoViewModel product, List<Public_Propertys> public_propertys, long leaf_category_id)
        {
            ParamItemRequest paramItem = new ParamItemRequest();

            Param param = new Param();

            paramItem.param = param;
            param.image_ids = product.media_id;

            param.title = product.ProductName;
            param.quantity = 0;

            param.item_no = product.ID;
            param.node_kdt_id = int.Parse(this.authority_id);

            //配送
            param.item_delivery_param = new item_delivery_param();

            //价格
            param.item_price_param.price = product.Price * 100;

            //类目 
            category_param category_Param = new category_param();
            category_properties category_Properties = new category_properties();
            category_Properties.publics = publics(product, public_propertys);

            category_Properties.leaf_category_id = leaf_category_id; //新版商品类目（V4版本）叶子类目id
            category_Param.category_properties = category_Properties;
            param.category_param = category_Param;

            HttpClientYouZanYun httpClient = GL.CreateYouZanYun();

            ItemResult result = await this.httpYzy.ItemAdd(authority_id, paramItem);
            if (!result.success)
            {
                this.Dispatcher.Invoke(() => {
                    SetErrorCell(rowIndex, result.message);
                });

                product.Msg = result.message;

                if(result.code == 221100020)
   
                      
                        DataDto dto2 = await httpClient.Import(product); 
                        //DataDto dto2 = await AddProductMap(dtoItem.data.items[0].item_id.ToString(), product);
                        if (dto2.error != null)
                        {
                            this.Dispatcher.Invoke(() => {
                                SetErrorCell(rowIndex, dto2.error.msg);
                            });

                            product.Msg = result.message;
                        }
                  
                }
            }
            else
            {
                //上传时不用编码，因为可以直接在产品表中查找 
                //DataDto dto2 = await AddProductMap(result.data.item_id.ToString(), product);
                DataDto dto2 = await httpClient.Import(product); ;
                if (dto2.error != null)
                {
                    this.Dispatcher.Invoke(() => {
                        SetErrorCell(rowIndex, dto2.error.msg);
                    });

                    product.Msg = result.message;
                }
            }

            this.data.CurrentValue++;
            if (this.data.CurrentValue == this.data.Total)
            {
                MessageBox.Show("导入完成");
                this.errorProductList.Clear();
            }
        }

        private List<publics> publics(ProductInfo product, List<Public_Propertys> public_propertys)
        {
            List<publics> _publics = new List<publics>();
            foreach (Public_Propertys pro in public_propertys)
            {
                Property property = pro.property;

                List<string> val_names = new List<string>();
                if (property.name == "产品剂型")
                {
                    val_names.Add(product.Model);
                }
                else if (property.name == "生产企业")
                {
                    val_names.Add(product.Manufacturer);
                }
                else if (property.name == "批准文号")
                {
                    val_names.Add(product.LiceseId);
                }
                else if (property.name == "有效期")
                {
                    val_names.Add(product.Validate.ToString());
                }
                else if (property.name.Contains("通用名"))
                {
                    val_names.Add(product.CommonTitle);
                }
                else if (property.name.Contains("规格"))
                {
                    val_names.Add(product.Spec);
                }
                else if (property.name.Contains("贮藏条件"))
                {
                    val_names.Add(product.ConditionOfStorage);
                }
                else if (property.name.Contains("单位"))
                {
                    val_names.Add(product.Unit);
                }
                else if (property.name.Contains("追溯码"))
                {
                    val_names.Add(product.Upc);
                }

                _publics.Add(new publics() { id = property.id, val_names = val_names });
            }

            return _publics;
        }

        private async Task<DataDto> AddProductMap(string app_medicine_code, ProductInfo product)
        { 
            ProductAndMapEntity productmap = new ProductAndMapEntity();

            ProductInfoMapEntity map = new ProductInfoMapEntity();
            map.Platform = PlatformEnum.YouZanYun;
            map.Upc = product.Upc;
            map.app_medicine_code = app_medicine_code;
            map.FKSN = 0;
            productmap.Map = map; 
            productmap.ProductInfo = product;

         
            DataDto dto = await GL.HttpClientManage.ProductSaveAndMap(productmap); 

            return dto;
        }

        private T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T childContent = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                childContent = v as T;
                if (childContent == null)
                {
                    childContent = GetVisualChild<T>(v);
                }
                if (childContent != null)
                { break; }
            }
            return childContent;
        }

        private void SetErrorCell(int rowIndex, string text)
        {
            DataGridRow row = (DataGridRow)this.dgv.ItemContainerGenerator.ContainerFromIndex(rowIndex);
            if (row != null)
            {
                DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);//函数调用，获取行中所有单元格的集合
                DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(0);//锁定选中单元格（重点）
                cell.Foreground = errorForeground;
                cell.Background = errorBackground;
                cell.Content = text;
            }
        }

        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            Slider slider = (Slider)sender;
            if (slider.Maximum == e.NewValue)
            {
                this.btnLoadImage.IsEnabled = false;
                this.btnImport.IsEnabled = false;
            }
        }
         
       
    }
}
